﻿/*
    This file is part of File Renamer.

    File Renamer is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 3.

    File Renamer is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
*/

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace FileRenamer
{
    public partial class MainForm : Form
    {
        private string SelectedPath;
        private FileMaster fMaster;
        private FileLoader fLoader;
        private List<char> Alphabet;
        
        public MainForm()
        {
            fMaster = new FileMaster();
            fLoader = new FileLoader();
            SelectedPath = "";

            Alphabet = new List<char>();
            char[] _Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();
            foreach (char c in _Alphabet)
            {
                Alphabet.Add(c);
            }

            InitializeComponent();

            cboPrefixType.SelectedIndex = 0;
            cboSufixType.SelectedIndex = 0;
            cboNameBaseType.SelectedIndex = 0;
            lblFileCount.Text = "Total Files: 0";
        }

        private void TimePickerFilterValueChanged()
        {
            if (OlderThanCheckBox.Checked && NewerThanCheckBox.Checked)
            {
                if (OlderThanTimePicker.Value < NewerThanTimePicker.Value)
                {
                    MessageBox.Show("The \"Older than\" date time value must be more than \"Newer than\" date time value");
                    ApplyFiltersButton.Enabled = false;
                }
                else
                {
                    ApplyFiltersButton.Enabled = true;
                }
            }
        }

        private void CheckBoxTimeFilterCheckedChanged()
        {
            if (OlderThanCheckBox.Checked && NewerThanCheckBox.Checked)
            {
                if (OlderThanTimePicker.Value < NewerThanTimePicker.Value)
                {
                    MessageBox.Show("The \"Older than\" date time value must be more than \"Newer than\" date time value");
                    ApplyFiltersButton.Enabled = false;
                }
                else
                {
                    ApplyFiltersButton.Enabled = true;
                }
            }
            else
            {
                ApplyFiltersButton.Enabled = true;
            }
        }

        private void OlderThanTimePicker_ValueChanged(object sender, EventArgs e)
        {
            TimePickerFilterValueChanged();
        }

        private void OlderThanCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            CheckBoxTimeFilterCheckedChanged();
        }

        private void NewerThanTimePicker_ValueChanged(object sender, EventArgs e)
        {
            TimePickerFilterValueChanged();
        }

        private void NewerThanCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            CheckBoxTimeFilterCheckedChanged();
        }

        private void LoadFilesButton_Click(object sender, EventArgs e)
        {
            ChooseFolderDialog.ShowDialog();
            this.SelectedPath = ChooseFolderDialog.SelectedPath;
            
            if (this.SelectedPath.Length == 0)
                return;

            CurrentFolder.Text = SelectedPath;
            fLoader.LoadFiles(SelectedPath);

            LoadExtensionsList();
            LoadInfoFromLoadedFilesToListBoxes();
            this.lblFileCount.Text = "Total Files: " + fLoader.loadedFiles.Length.ToString();
        }

        private void ChooseFolderDialog_HelpRequest(object sender, EventArgs e)
        {

        }

        private void LoadExtensionsList()
        {
            ExtensionsListBox.Items.Clear();
            //Filling list of loaded files extensions
            for (int i = 0; i < fLoader.ExtractedFileExtensions.Length; i++)
            {
                ExtensionsListBox.Items.Add(fLoader.ExtractedFileExtensions[i]);
            }
        }

        private void LoadInfoFromLoadedFilesToListBoxes()
        {
            
            LoadedFilesListView.Items.Clear();
            //Filling loaded files list with loaded files
            for (int i = 0; i < fLoader.loadedFiles.Length; i++)
            {
                String[] lFile = new String[3];
                lFile[0] = fLoader.loadedFiles[i].Name;
                lFile[1] = fLoader.loadedFiles[i].Extension;
                lFile[2] = fLoader.loadedFiles[i].CreationTime.ToString();
                ListViewItem listFile = new ListViewItem(lFile);

                LoadedFilesListView.Items.Add(listFile);
            }            
        }

        private void ApplyFiltersButton_Click(object sender, EventArgs e)
        {
            if (SelectedPath.Length == 0)
                return;

            string[] filterExtensions;
            List<string> filterExtensionsList = new List<string>();
            //Generating array of extenstions
            for (int i = 0; i < fLoader.ExtractedFileExtensions.Length; i++)
            {
                if (ExtensionsListBox.SelectedItems.Contains(fLoader.ExtractedFileExtensions[i]))
                    filterExtensionsList.Add(fLoader.ExtractedFileExtensions[i]);
            }

            filterExtensions = filterExtensionsList.ToArray();

            bool filterByOlderThan  = OlderThanCheckBox.Checked;
            bool filterByNewerThan  = NewerThanCheckBox.Checked;
            bool filterByExtensions = ExtensionFilterCheckBox.Checked;

            fLoader.LoadFilesFiltered(this.SelectedPath, filterByExtensions, filterExtensions,
                filterByOlderThan, filterByNewerThan, OlderThanTimePicker.Value, NewerThanTimePicker.Value);

            LoadInfoFromLoadedFilesToListBoxes();        
        }

        private void DeleteButton_Click(object sender, EventArgs e)
        {   
            if (DialogResult.OK == MessageBox.Show("Do you really want to delete files", "", MessageBoxButtons.OK | MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
            {
                fLoader.DeleteFiles();
                ApplyFiltersButton_Click(this,null);
            }
        }

        private void AboutButton_Click(object sender, EventArgs e)
        {
            AboutBox1 ab = new AboutBox1();
            ab.ShowDialog();
        }

        private void AlphabeticPrefixRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            if (AlphabeticPrefixRadioButton.Checked)
            {
                NumericPrefixRadioButton.Checked = false;
                StaticPrefixRadioButton.Checked = false;
            }
        }

        private void NumericPrefixRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            if (NumericPrefixRadioButton.Checked)
            {
                AlphabeticPrefixRadioButton.Checked = false;
                StaticPrefixRadioButton.Checked = false;
            }
        }

        private void StaticPrefixRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            if (StaticPrefixRadioButton.Checked)
            {
                AlphabeticPrefixRadioButton.Checked = false;
                NumericPrefixRadioButton.Checked = false;
            }
        }

        private void AlphabeticPrefixTextBox_TextChanged(object sender, EventArgs e)
        {
            String text = AlphabeticPrefixTextBox.Text;
 
            for (int i = 0; i < text.Length; i++)
            {
                if (!Alphabet.Contains(text[i]))
                {
                    text = text.Remove(i, 1);
                }
            }

            AlphabeticPrefixTextBox.Text = text;
        }

        private void PreviewButton_Click(object sender, EventArgs e)
        {
            fMaster.UpadateFiles(fLoader.loadedFiles);
            ApplyRenameChangesForPreview();

            LoadPreviewFileNamesInToListView();
        }

        //Calls File Master functions for adding prefix, sufix... those that user wants
        //For preview
        private void ApplyRenameChangesForPreview()
        {
            //Insert Delete section
            if (this.InsertRadioButton.Checked)
            {
                int position = (int)this.InsertAtPositionUpDown.Value;
                String text = this.InsertTextBox.Text;
                fMaster.InsertTextInFileName(position, text);
            }

            if (this.DeleteRadioButton.Checked)
            {
                int position = (int)this.DeleteFromPositionUpDown.Value;
                int symbolsNumber = (int)this.DeleteSymbolsNumberUpDown.Value;
                fMaster.DeleteSybmols(position, symbolsNumber);
            }
            //End of Insert Delete Section

            //Modify file name section

            if (StaticFileNameRadioButton.Checked)
            {
                fMaster.ModifyNames_Static(StaticFileNameTextBox.Text);
            }

            if (NumericFileNameRadioButton.Checked)
            {
                PREFIX_SUFIX_TYPE nameType = PREFIX_SUFIX_TYPE.ASC;

                switch (cboNameBaseType.SelectedIndex)
                {
                    case 0:
                        nameType = PREFIX_SUFIX_TYPE.ASC;
                        break;
                    case 1:
                        nameType = PREFIX_SUFIX_TYPE.DES;
                        break;
                    case 2:
                        nameType = PREFIX_SUFIX_TYPE.RND;
                        break;
                }

                int startFrom = (int)NumericFileNameStartFromUpDown.Value;
                int step = (int)NumericFileNameStepUpDown.Value;
                String paddingMask = FileNamePaddingMask.Text;

                fMaster.ModifyNames_Numeric(startFrom, step, nameType, paddingMask);

            }
            
            //End of modify file name section

            //Prefix Sufix section    
            /*Prefix part*/
            if (NumericPrefixRadioButton.Checked)
            {
                PREFIX_SUFIX_TYPE psType = PREFIX_SUFIX_TYPE.ASC;

                switch (cboPrefixType.SelectedIndex)
                {
                    case 0:
                        psType = PREFIX_SUFIX_TYPE.ASC;
                        break;
                    case 1:
                        psType = PREFIX_SUFIX_TYPE.DES;
                        break;
                    case 2:
                        psType = PREFIX_SUFIX_TYPE.RND;
                        break;
                }

                int startFrom = (int)NumericPrefixStartFromUpDown.Value;
                int step = (int)NumericPrefixStepUpDown.Value;
                String paddingMask = PrefixPaddingMask.Text;

                fMaster.AddNumericPrefix(startFrom, step, psType, paddingMask);                
            }

            if (StaticPrefixRadioButton.Checked)
            {
                String prefix = StaticPrefixTextBox.Text;
                fMaster.AddStaticPrefix(prefix);
            }

            /*Sufix part*/
            if (NumericSufixRadioButton.Checked)
            {
                PREFIX_SUFIX_TYPE psType = PREFIX_SUFIX_TYPE.ASC;

                switch (cboSufixType.SelectedIndex)
                {
                    case 0:
                        psType = PREFIX_SUFIX_TYPE.ASC;
                        break;
                    case 1:
                        psType = PREFIX_SUFIX_TYPE.DES;
                        break;
                    case 2:
                        psType = PREFIX_SUFIX_TYPE.RND;
                        break;
                }

                int startFrom = (int)NumericSufixStartFromUpDown.Value;
                int step = (int)NumericSufixStepUpDown.Value;
                String paddingMask = SufixPaddingMask.Text;

                fMaster.AddNumericSufix(startFrom, step, psType, paddingMask);
            }

            if (StaticSufixRadioButton.Checked)
            {
                String Sufix = StaticSufixTextBox.Text;
                fMaster.AddStaticSufix(Sufix);
            }
            //End of Prefix Sufix section
        }

        //Loads file names in to list view, for preview of changes to happen
        private void LoadPreviewFileNamesInToListView()
        {
            PreviewFilesListView.Items.Clear();

            String[] fileNamePreviews = fMaster.GetChangedFileNamesForPreview();

            for (int i = 0; i < fileNamePreviews.Length; i++)
            {
                ListViewItem fileItem = new ListViewItem(fileNamePreviews[i]);
                PreviewFilesListView.Items.Add(fileItem);
            }
        }

        private void InsertRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            if (InsertRadioButton.Checked)
            {
                DeleteRadioButton.Checked = false;
            }
        }

        private void DeleteRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            if (DeleteRadioButton.Checked)
            {
                InsertRadioButton.Checked = false;
            }
        }

        private void RenamingOptionTabs_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if ((string) this.RenamingOptionTabs.SelectedTab.Tag == "NameModification")
            {
                if (!this.AlphabeticPrefixRadioButton.Checked &&
                    !this.NumericPrefixRadioButton.Checked &&
                    !this.AlphabeticSufixRadioButton.Checked &&
                    !this.NumericSufixRadioButton.Checked)
                {//Disabling file name changing with new static text to avoid files with same name
                    this.StaticFileNameRadioButton.Checked = false;
                    this.StaticFileNameRadioButton.Enabled = false;
                    this.DeleteRadioButton.Checked = false;
                    this.DeleteRadioButton.Enabled = false;
                    this.StaticFileNameErrorMessage.Text = "You have to select nonstatic prefix or sufix to change file name to static one or delete symbols, for to avoid files with same name.";
                }
                else
                {
                    this.StaticFileNameRadioButton.Enabled = true;
                    this.DeleteRadioButton.Enabled = true;
                    this.StaticFileNameErrorMessage.Text = "";
                }
            }
        }

        private void PrefixResetButton_Click(object sender, EventArgs e)
        {
            this.AlphabeticPrefixRadioButton.Checked = false;
            this.NumericPrefixRadioButton.Checked = false;
            this.StaticPrefixRadioButton.Checked = false;
        }

        private void SufixResetButton_Click(object sender, EventArgs e)
        {
            this.AlphabeticSufixRadioButton.Checked = false;
            this.NumericSufixRadioButton.Checked = false;
            this.StaticSufixRadioButton.Checked = false;
        }

        private void ModifyFileNameResetButton_Click(object sender, EventArgs e)
        {
            this.NumericFileNameRadioButton.Checked = false;
            this.AlphabeticFileNameRadioButton.Checked = false;
            this.StaticFileNameRadioButton.Checked = false;
            this.InsertRadioButton.Checked = false;
            this.DeleteRadioButton.Checked = false;
        }

        private void ResetInsertDeleteButton_Click(object sender, EventArgs e)
        {

        }

        private void RenameButton_Click(object sender, EventArgs e)
        {
            fMaster.UpadateFiles(fLoader.loadedFiles);
            ApplyRenameChangesForPreview();
            if (fMaster.CheckFileNames())
            {
                fMaster.Rename();
                fLoader.LoadFiles(SelectedPath);

                // Reload file list
                LoadExtensionsList();
                LoadInfoFromLoadedFilesToListBoxes();
                this.lblFileCount.Text = "Total Files: " + fLoader.loadedFiles.Length.ToString();

                //Clear preview
                this.PreviewFilesListView.Items.Clear();
            }
            else
            {
                MessageBox.Show("Selected settings produce duplicate file names. \n                  Please change settings.", "Input Error");
            }
        }

    }
}
